package com.waymap.controller;

import com.github.pagehelper.PageInfo;
import com.waymap.common.Constant;
import com.waymap.common.dataGridResult.DataGridResult;
import com.waymap.common.vo.ItemsVo;
import com.waymap.common.vo.SkuItemVo;
import com.waymap.domain.InventorysAdjust;
import com.waymap.domain.RecomDto;
import com.waymap.domain.User;
import com.waymap.service.ItemInventoryService;
import com.waymap.service.ItemService;
import com.waymap.service.LocationBinsService;
import com.waymap.service.UserService;
import com.waymap.utils.AuthonTokenUtil;
import com.waymap.utils.CommonEnum;
import com.waymap.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(
        value = "WMS系统",
        tags = {"WMS-库存管理接口"}
)
@CrossOrigin
@RestController
@RequestMapping("/item")
public class ItemController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ItemService itemService;

    @Autowired
    private UserService userService;
    @Autowired
    private ItemInventoryService itemInventoryService;
    @Autowired
    private LocationBinsService locationBinsService;

    @ApiOperation(value = "库存查询列表")
    @RequestMapping(value = "/getItemPage", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> getItemPage(@ApiParam(value = "商品条码") @RequestParam(required = false) String upc,
                                           @ApiParam(value = "sku编码") @RequestParam(required = false) String sku,
                                           @ApiParam(value = "商品名称") @RequestParam(required = false) String itemDescription,
                                           @ApiParam(value = "库位") @RequestParam(required = false) String binName,
                                           @ApiParam(value = "客户account_id(true)") @RequestParam String accountId,
                                           @ApiParam(value = "每页显示数量(true)") @RequestParam Integer pageSize,
                                           @ApiParam(value = "页数(true)") @RequestParam Integer pageNum,
                                           @ApiParam(value = "当前用户token") @RequestParam(required = false) String token,
                                           @ApiParam(value = "用户Id") @RequestParam(required = false) String userId) {


        Map<String, Object> authonMap = AuthonTokenUtil.checkToken(token, userId);
        if ((authonMap != null) && ((Constant.NO).equals(authonMap.get("isAvailable")))) {
            return ResponseEntity.ok(authonMap);
        }
        User currentUser = userService.getUserInfoByToken(token);
        Map<String, Object> param = new HashMap(16);
        if (!StringUtil.isNullOrEmpty(upc)) {
            param.put("upc", upc.trim());
        }
        if (!StringUtil.isNullOrEmpty(sku)) {
            param.put("itemName", sku.trim());
        }
        if (!StringUtil.isNullOrEmpty(itemDescription)) {
            param.put("itemDescription", itemDescription.trim());
        }
        if (!StringUtil.isNullOrEmpty(binName)) {
            param.put("binName", binName.trim());
        }

        param.put("accountId", accountId);
        param.put("pageSize", pageSize);
        param.put("pageNum", pageNum);
        param.put("location", currentUser.getLocationId());

        List<ItemsVo> list = itemService.getItemPage(param);
        Map map = new HashMap(16);
        if (null != list && list.size() > 0) {
            logger.info("-------------产品分页查询成功并返回-----------------------" + list.size() + "条");
            PageInfo<ItemsVo> pageInfo = new PageInfo<>(list);
            if (null != pageInfo) {
                SkuItemVo skuItem = itemService.getskuItemCount(param);
                if (null != skuItem) {
                    map.put("skuCount", skuItem.getSkuCount());
                    map.put("itemTotal", skuItem.getItemTotal());
                }
                DataGridResult data = new DataGridResult();
                data.setRows(pageInfo.getList());
                data.setPageSize(pageInfo.getPageSize());
                data.setPageNum(pageInfo.getPageNum());
                data.setEndRow(pageInfo.getEndRow());
                data.setStartRow(pageInfo.getStartRow());
                data.setTotal(pageInfo.getTotal());
                map.put("result", data);
                map.put("status", CommonEnum.value("eSuccess"));
                map.put("msg", CommonEnum.value("eSMessage"));
            }

        } else {
            map.put("status", CommonEnum.value("eNotFind"));
            map.put("msg", CommonEnum.value("notFind"));

        }
        return ResponseEntity.ok(map);
    }


    @ApiOperation(value = "根据SKU查询Item明细")
    @RequestMapping(value = "/findItemDetailsBySku", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> findItemDetailsBySku(@ApiParam(value = "商品SKU") @RequestParam(required = true) String itemSku,
                                                    @ApiParam(value = "当前用户token") @RequestParam(required = true) String token,
                                                    @ApiParam(value = "用户Id") @RequestParam(required = true) String userId) {
        Map<String, Object> authonMap = AuthonTokenUtil.checkToken(token, userId);
        System.out.println(authonMap);
        User currentUser = null;
        String accountId = null;
        if ((authonMap != null) && ((Constant.NO).equals(authonMap.get("isAvailable")))) {
            return ResponseEntity.ok(authonMap);
        } else {
            currentUser = userService.getUserInfoByToken(token);
            if (currentUser == null) {
                authonMap.put("isAvailable", Constant.NO);
                authonMap.put("errorCode", Constant.TOKEN_ERRCODE_EXPIRE);
                authonMap.put("msg", "签名过期");
                return ResponseEntity.ok(authonMap);
            }
            accountId = currentUser.getAccountId();
        }
        Map<String, Object> param = new HashMap(16);
        param.put("sku", itemSku);
        param.put("accountId", accountId);
        Map<String, Object> map = new HashMap(16);
        map.put("result", itemService.findLotNumberByItemId(param));
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", CommonEnum.value("eSMessage"));
        return ResponseEntity.ok(map);
    }

    @ApiOperation(value = "调整库存")
    @RequestMapping(value = "/adjustStock", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> adjustStock(@ApiParam(value = "商品Id") @RequestParam(required = true) Integer itemId,
                                           @ApiParam(value = "库位") @RequestParam(required = true) Integer binId,
                                           @ApiParam(value = "批次") @RequestParam(required = false) String lotNumber,
                                           @ApiParam(value = "调整类型（1 入口  0 出库）") @RequestParam(required = true) Integer stockType,
                                           @ApiParam(value = "数量") @RequestParam(required = true) Integer adjustNum,
                                           @ApiParam(value = "当前用户token") @RequestParam(required = true) String token,
                                           @ApiParam(value = "用户Id") @RequestParam(required = true) String userId) {
        Map<String, Object> authonMap = AuthonTokenUtil.checkToken(token, userId);
        User currentUser = null;
        String accountId = null;
        if ((authonMap != null) && ((Constant.NO).equals(authonMap.get("isAvailable")))) {
            return ResponseEntity.ok(authonMap);
        } else {
            currentUser = userService.getUserInfoByToken(token);
            if (currentUser == null) {
                authonMap.put("isAvailable", Constant.NO);
                authonMap.put("errorCode", Constant.TOKEN_ERRCODE_EXPIRE);
                authonMap.put("msg", "签名过期");
                return ResponseEntity.ok(authonMap);
            }
            accountId = currentUser.getAccountId();
        }
        InventorysAdjust inventorysAdjust = new InventorysAdjust();
        inventorysAdjust.setItemId(itemId);
        inventorysAdjust.setStockType(stockType);
        inventorysAdjust.setBinId(binId);
        inventorysAdjust.setLocationId(currentUser.getLocationId());
        inventorysAdjust.setCreateByUser(currentUser.getUserName());
        inventorysAdjust.setAdjustNum(adjustNum);
        inventorysAdjust.setAccountId(accountId);
        inventorysAdjust.setLotNumber(lotNumber);
        try {
            itemInventoryService.InventorysAdjust(inventorysAdjust);
        } catch (Exception e) {
            logger.debug("itemIderror");
        }
        Map<String, Object> map = new HashMap(16);
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", CommonEnum.value("eSMessage"));
        return ResponseEntity.ok(map);
    }

    /**/
    @ApiOperation(value = "查询推荐库位")
    @RequestMapping(value = "/binList", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map> selectRecommendBin(@ApiParam(value = "token") @RequestParam(required = true) String token,
                                                  @ApiParam(value = "userId") @RequestParam(required = true) String userId,
                                                  @ApiParam(value = "sku") @RequestParam(required = true) String sku
                                                  ) {
        Map<String, Object> authonMap = AuthonTokenUtil.checkToken(token, userId);
        if ((authonMap != null) && ((Constant.NO).equals(authonMap.get("isAvailable")))) {
            return ResponseEntity.ok(authonMap);
        }
        RecomDto recomDto = new RecomDto();
        User currentUser = userService.getUserInfoByToken(token);
        recomDto.setAccountId(currentUser.getAccountId());
        recomDto.setLocationId(currentUser.getLocationId());
        recomDto.setSku(sku);
        return locationBinsService.selectRecommondBins(recomDto);
    }

}
